﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using NPOI.OpenXmlFormats;
using NPOI.POIFS.Crypt.Dsig;
using SyncService.Abstractions.Events;
using SyncService.Abstractions.Services;
using SyncService.Core.Utils;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

namespace SyncService.Core.Services
{
    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "zeroResult")]
    public class ZeroResultSerive : AssetSyncServiceBase
    {
        private IMemoryCache? _cache = null;
        private ILogger<ZeroResultSerive> _logger = null;
        public ZeroResultSerive() : base(YdConstants.YIDEA, "Sap", "")
        {
        }
        protected override void InitializeContext()
        {
            base.InitializeContext();
            _cache = Resolver.Resolve<IMemoryCache>();
            _logger = Resolver.Resolve<ILogger<ZeroResultSerive>>();
        }
        public override void ExecuteCore()
        {
            AssetSyncEvent Data = (AssetSyncEvent)State!;
            var serialNo = Data.Data["SerialNo"].ToString();
            var form = UserDefines.First(e => e.Name == "0元列管入库单");
            var zeroSerialNoFiled = ExtendFields.First(e => e.ObjectType == 57 && e.Name == "入库单收货单号");
            if (serialNo.Substring(0, 3) == "AIS")
            {
                var assetInStorages = YideaClient.GetAssetInStorages(new QueryParam() { FilterString = "extensionFilters=[{label:\"serialNo\",operator:\"EqualTo\",value:\"" + serialNo + "\"}]" }).ToList();
                if (assetInStorages.Count > 0)
                {
                    var assetInStorage = assetInStorages[0];
                    var dataJson = JsonNode.Parse(assetInStorage.ExtraData["dataJson"].ToString()).AsObject();
                    if (dataJson[zeroSerialNoFiled.FieldId] != null)
                    {
                        var zeroSerialNo = dataJson[zeroSerialNoFiled.FieldId].ToString();
                        if (zeroSerialNo.Substring(0, 3) != "ZER")
                        {
                            return;
                        }
                        //回写0元列管表单资产编码
                        //取字段名
                        var assetListFiled = ExtendFields.First(e => e.ObjectType == 57 && e.Name == "资产列表");
                        var assetBarcodeFiled = ExtendFields.First(e => e.ObjectType == 57 && e.Name == "资产编码");
                        var formFileds = ExtendFields.Where(e => e.ObjectType == 57 && e.FieldType != ExtendFieldType.Input).ToList();
                        var zeroField = UserDefines.First(e => e.Name == "0元列管入库单");
                        var zeroDatas = YideaClient.GetCustomizedFormDatas(formId: zeroField.Id, new QueryParam()
                        {
                            FilterString = "[{\"field\":\"serialNo\",\"type\":\"input\",\"label\":\"单据号\",\"opt\":\"Equal\",\"val\":\"" + zeroSerialNo + "\"}]"
                        }).ToList();
                        var zeroData = new JsonArray();
                        if (zeroDatas.Count > 0)
                        {
                            var zeroDataJson = JsonNode.Parse(zeroDatas[0].Data["dataJson"].ToString()).AsObject();
                            zeroData = zeroDataJson[assetListFiled.FieldId].AsArray();
                        }

                        CustomizedFormData flowStateForm = new CustomizedFormData();
                        flowStateForm.FormId = form!.Id;
                        flowStateForm.WebhookPush = false;
                        flowStateForm.SerialNo = zeroSerialNo;
                        JsonObject customizedData = new JsonObject();
                        var item = new JsonArray();
                        JsonArray assets = assetInStorage.ExtraData["assets"].AsArray();
                        foreach (var asset in assets)
                        {
                            int i = 0;
                            var assetItem = new JsonObject();
                            assetItem[assetBarcodeFiled.FieldId] = new JsonObject { ["value"] = asset["barcode"].ToString() };
                            foreach (var field in formFileds)
                            {
                                if (zeroData[i][field.FieldId] == null || zeroData[i][field.FieldId].ToString() == "{}")
                                {
                                    continue;
                                }
                                switch (field.FieldType)
                                {
                                    case ExtendFieldType.Table:
                                        assetItem[field.FieldId] = new JsonObject { ["value"] = zeroData[i][field.FieldId]?.ToString() };
                                        break;
                                    case ExtendFieldType.Select:
                                        string str = string.Empty;
                                        str = ExcuteStr(zeroData[i]?[field.FieldId]);
                                        assetItem[field.FieldId] = new JsonObject { ["value"] = str };
                                        break;
                                    case ExtendFieldType.EmployeeSelect:
                                        assetItem[field.FieldId] = new JsonObject { ["value"] = zeroData[i][field.FieldId]?["code"]?.ToString() };
                                        break;
                                    case ExtendFieldType.InputInt:
                                        assetItem[field.FieldId] = new JsonObject { ["value"] = zeroData[i][field.FieldId]?.ToString() };
                                        break;
                                }
                            }
                            item.Add(assetItem);
                            i++;

                        }
                        customizedData = new JsonObject()
                        {
                            [assetListFiled.FieldId] = item

                        };
                        flowStateForm.Data = customizedData;
                        var updateTableResponse = YideaClient.UpdateCustomizedFormData(flowStateForm, null);
                        _logger.LogInformation("更新0元列管资产编码结果：" + updateTableResponse);
                    }
                }
            }
        }

        private string ExcuteStr(JsonNode json)
        {
            string strValue = string.Empty;
            if (json is JsonValue valueNode && valueNode.TryGetValue(out string? stringValue) && string.IsNullOrEmpty(stringValue))
            {
                return strValue = "";
            }
            else
            {
                return json?["value"]?.ToString();
            }
        }
    }
}
